<template>
  <div class="crud-demo-container">
    <a-card title="用户管理 (基于VXE-Table)" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="用户名">
            <a-input v-model:value="searchForm.username" placeholder="请输入用户名" allowClear />
          </a-form-item>
          <a-form-item label="部门">
            <a-select v-model:value="searchForm.department" placeholder="请选择部门" style="width: 200px" allowClear>
              <a-select-option value="development">研发部</a-select-option>
              <a-select-option value="marketing">市场部</a-select-option>
              <a-select-option value="finance">财务部</a-select-option>
              <a-select-option value="hr">人力资源部</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                查询
              </a-button>
              <a-button @click="resetSearch">
                <template #icon><reload-outlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="table-toolbar">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            新增用户
          </a-button>
          <a-button type="danger" :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
          <a-button @click="refreshTable">
            <template #icon><sync-outlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- VXE表格 -->
      <vxe-table
        ref="xTable"
        border
        stripe
        resizable
        highlight-hover-row
        height="450"
        :data="tableData"
        :checkbox-config="{highlight: true, trigger: 'row'}"
        @checkbox-change="onCheckboxChange"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column field="id" title="ID" width="80"></vxe-column>
        <vxe-column field="username" title="用户名"></vxe-column>
        <vxe-column field="realName" title="真实姓名"></vxe-column>
        <vxe-column field="phone" title="手机号码"></vxe-column>
        <vxe-column field="email" title="邮箱"></vxe-column>
        <vxe-column field="departmentName" title="部门"></vxe-column>
        <vxe-column field="status" title="状态">
          <template #default="{row}">
            <a-tag :color="row.status === '1' ? 'success' : 'error'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </a-tag>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="200">
          <template #default="{row}">
            <a-space>
              <a-button type="link" size="small" @click="handleView(row)">
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEdit(row)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定删除该条记录吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(row)"
              >
                <a-button type="link" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </vxe-column>
      </vxe-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <a-pagination
          :current="pagination.current"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :page-size-options="['10', '20', '30', '40']"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
          show-total
        />
      </div>

      <!-- 表单弹窗 -->
      <a-modal
        v-model:open="modalVisible"
        :title="modalType === 'add' ? '新增用户' : modalType === 'edit' ? '编辑用户' : '查看用户'"
        width="700px"
        :maskClosable="false"
        :confirmLoading="confirmLoading"
        @ok="handleModalOk"
      >
        <a-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          :label-col="{span: 4}"
          :wrapper-col="{span: 18}"
        >
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="formData.username" placeholder="请输入用户名" :disabled="modalType === 'view'" />
          </a-form-item>
          <a-form-item label="真实姓名" name="realName">
            <a-input v-model:value="formData.realName" placeholder="请输入真实姓名" :disabled="modalType === 'view'" />
          </a-form-item>
          <a-form-item label="手机号" name="phone">
            <a-input v-model:value="formData.phone" placeholder="请输入手机号" :disabled="modalType === 'view'" />
          </a-form-item>
          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" :disabled="modalType === 'view'" />
          </a-form-item>
          <a-form-item label="部门" name="department">
            <a-select v-model:value="formData.department" placeholder="请选择部门" style="width: 100%" :disabled="modalType === 'view'">
              <a-select-option value="development">研发部</a-select-option>
              <a-select-option value="marketing">市场部</a-select-option>
              <a-select-option value="finance">财务部</a-select-option>
              <a-select-option value="hr">人力资源部</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态" name="status">
            <a-radio-group v-model:value="formData.status" :disabled="modalType === 'view'">
              <a-radio value="1">启用</a-radio>
              <a-radio value="0">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="formData.remark" :rows="3" placeholder="请输入备注信息" :disabled="modalType === 'view'" />
          </a-form-item>
        </a-form>

        <template #footer>
          <a-button v-if="modalType === 'view'" @click="modalVisible = false">关闭</a-button>
          <template v-else>
            <a-button @click="modalVisible = false">取消</a-button>
            <a-button type="primary" :loading="confirmLoading" @click="handleModalOk">确定</a-button>
          </template>
        </template>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { VxeTableInstance } from 'vxe-table';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  DeleteOutlined,
  SyncOutlined
} from '@ant-design/icons-vue';

// 表格数据接口
interface UserInfo {
  id: string | number;
  username: string;
  realName: string;
  phone: string;
  email: string;
  department: string;
  departmentName: string;
  status: string;
  remark?: string;
}

// 搜索表单
const searchForm = reactive({
  username: '',
  department: undefined
});

// 重置搜索条件
const resetSearch = () => {
  searchForm.username = '';
  searchForm.department = undefined;
  handleSearch();
};

// 表格相关
const xTable = ref<VxeTableInstance>();
const loading = ref(false);
const tableData = ref<UserInfo[]>([]);
const selectedRowKeys = ref<(string | number)[]>([]);
const selectedRows = ref<UserInfo[]>([]);

// 持久化的模拟数据
const persistentData = ref<UserInfo[]>([
  {
    id: '1',
    username: 'admin',
    realName: '管理员',
    phone: '13800138000',
    email: 'admin@example.com',
    department: 'development',
    departmentName: '研发部',
    status: '1',
    remark: '系统管理员账号'
  },
  {
    id: '2',
    username: 'zhangsan',
    realName: '张三',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    department: 'marketing',
    departmentName: '市场部',
    status: '1',
    remark: '市场部员工'
  },
  {
    id: '3',
    username: 'lisi',
    realName: '李四',
    phone: '13800138002',
    email: 'lisi@example.com',
    department: 'finance',
    departmentName: '财务部',
    status: '0',
    remark: '财务部员工'
  },
  {
    id: '4',
    username: 'wangwu',
    realName: '王五',
    phone: '13800138003',
    email: 'wangwu@example.com',
    department: 'hr',
    departmentName: '人力资源部',
    status: '1',
    remark: '人力资源部员工'
  }
]);

// 分页相关
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
});

// 多选框事件
const onCheckboxChange = (params: { records: UserInfo[] }) => {
  selectedRows.value = params.records;
  selectedRowKeys.value = params.records.map(item => item.id);
};

// 页码改变
const handlePageChange = (page: number, pageSize?: number) => {
  pagination.current = page;
  if (pageSize) {
    pagination.pageSize = pageSize;
  }
  fetchData();
};

// 每页条数改变
const handleSizeChange = (_: any, size: number) => {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchData();
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 刷新表格
const refreshTable = () => {
  fetchData();
};

// 表单相关
const formRef = ref<FormInstance>();
const modalVisible = ref(false);
const confirmLoading = ref(false);
const modalType = ref<'add' | 'edit' | 'view'>('add');
const formData = reactive<UserInfo>({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  department: '',
  departmentName: '',
  status: '1',
  remark: ''
});

// 表单校验规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 新增
const handleAdd = () => {
  resetFormData();
  modalType.value = 'add';
  modalVisible.value = true;
};

// 查看
const handleView = (row: UserInfo) => {
  Object.assign(formData, row);
  modalType.value = 'view';
  modalVisible.value = true;
};

// 编辑
const handleEdit = (row: UserInfo) => {
  Object.assign(formData, row);
  modalType.value = 'edit';
  modalVisible.value = true;
};

// 删除
const handleDelete = (row: UserInfo) => {
  // 从持久化数据中删除
  const index = persistentData.value.findIndex(item => item.id === row.id);
  if (index > -1) {
    persistentData.value.splice(index, 1);
    message.success(`删除成功: ${row.username}`);
    fetchData();
  } else {
    message.error('未找到要删除的记录');
  }
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请至少选择一条记录');
    return;
  }

  // 从持久化数据中批量删除
  persistentData.value = persistentData.value.filter(
    item => !selectedRowKeys.value.includes(item.id)
  );

  message.success(`批量删除成功，共 ${selectedRowKeys.value.length} 条记录`);
  selectedRowKeys.value = [];
  selectedRows.value = [];
  fetchData();
};

// 弹窗确认
const handleModalOk = () => {
  if (modalType.value === 'view') {
    modalVisible.value = false;
    return;
  }

  formRef.value?.validate().then(() => {
    confirmLoading.value = true;

    // 根据部门ID找到部门名称
    const departmentMap = {
      'development': '研发部',
      'marketing': '市场部',
      'finance': '财务部',
      'hr': '人力资源部'
    };
    formData.departmentName = departmentMap[formData.department] || '';

    // 模拟API提交
    setTimeout(() => {
      if (modalType.value === 'add') {
        // 生成一个新ID
        const newId = String(Math.max(...persistentData.value.map(item => Number(item.id))) + 1);
        const newRecord = { ...formData, id: newId };
        persistentData.value.push(newRecord);
        message.success('新增成功');
      } else if (modalType.value === 'edit') {
        // 更新已有记录
        const index = persistentData.value.findIndex(item => item.id === formData.id);
        if (index > -1) {
          persistentData.value[index] = { ...formData };
          message.success('更新成功');
        } else {
          message.error('未找到要编辑的记录');
        }
      }

      modalVisible.value = false;
      confirmLoading.value = false;
      fetchData();
    }, 500);
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    username: '',
    realName: '',
    phone: '',
    email: '',
    department: '',
    departmentName: '',
    status: '1',
    remark: ''
  });

  // 重置表单校验状态
  formRef.value?.resetFields();
};

// 模拟获取数据
const fetchData = () => {
  loading.value = true;

  // 模拟后端接口调用
  setTimeout(() => {
    // 使用持久化数据
    let result = [...persistentData.value];

    // 筛选
    if (searchForm.username) {
      result = result.filter(item => item.username.includes(searchForm.username));
    }
    if (searchForm.department) {
      result = result.filter(item => item.department === searchForm.department);
    }

    // 设置分页数据
    pagination.total = result.length;

    // 模拟分页
    const startIndex = (pagination.current - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;
    tableData.value = result.slice(startIndex, endIndex);

    loading.value = false;
  }, 500);
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.crud-demo-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}
</style>